package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.List;

/**
 * 客户端处理器，处理与客户端的通信
 */
public class ClientHandler implements Runnable {
    private Socket clientSocket;
    private PrintWriter out;
    private BufferedReader in;
    private List<ClientHandler> clientHandlers;
    private String role; // 角色：customer, employee, boss, supplier
    private String userId; // 用户ID
    
    public ClientHandler(Socket socket, List<ClientHandler> clients) {
        this.clientSocket = socket;
        this.clientHandlers = clients;
    }
    
    public void run() {
        try {
            out = new PrintWriter(clientSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            
            String inputLine;
            // 首先读取客户端角色信息
            if ((inputLine = in.readLine()) != null) {
                String[] parts = inputLine.split(":");
                if (parts.length == 2) {
                    this.role = parts[0];
                    this.userId = parts[1];
                    System.out.println("角色确认: " + role + ", 用户ID: " + userId);
                    out.println("已连接到服务器，角色: " + role);
                }
            }
            
            // 处理客户端消息
            while ((inputLine = in.readLine()) != null) {
                System.out.println("收到来自" + role + "(" + userId + ")的消息: " + inputLine);
                
                // 解析消息并处理
                processMessage(inputLine);
                
                // 如果是退出命令，断开连接
                if ("exit".equalsIgnoreCase(inputLine)) {
                    break;
                }
            }
            
            // 清理资源
            in.close();
            out.close();
            clientSocket.close();
            clientHandlers.remove(this);
            System.out.println(role + "(" + userId + ")已断开连接");
            
        } catch (IOException e) {
            System.err.println("客户端处理错误: " + e.getMessage());
        }
    }
    
    // 处理客户端消息
    private void processMessage(String message) {
        // 消息格式：操作类型:参数1:参数2:...
        String[] parts = message.split(":");
        if (parts.length == 0) return;
        
        switch (parts[0]) {
            case "restockRequest":
                // 补货请求：restockRequest:商品ID:数量:供应商ID
                if (parts.length >= 4 && "employee".equals(role)) {
                    String productId = parts[1];
                    String quantity = parts[2];
                    String supplierId = parts[3];
                    
                    // 转发给指定供应商
                    String supplierMessage = "restockRequest:" + userId + ":" + productId + ":" + quantity;
                    Server.sendToClient(supplierMessage, supplierId);
                    out.println("已向供应商发送补货请求");
                }
                break;
            case "restockConfirm":
                // 补货确认：restockConfirm:商品ID:数量
                if (parts.length >= 3 && "supplier".equals(role)) {
                    String productId = parts[1];
                    String quantity = parts[2];
                    
                    // 发送给老板
                    String bossMessage = "restockConfirm:" + userId + ":" + productId + ":" + quantity;
                    Server.broadcastToRole(bossMessage, "boss");
                    out.println("已确认补货并通知老板");
                }
                break;
            case "broadcastToEmployees":
                // 老板广播给所有员工
                if (parts.length >= 2 && "boss".equals(role)) {
                    String content = message.substring(parts[0].length() + 1);
                    Server.broadcastToRole("bossNotice:" + content, "employee");
                    out.println("已向所有员工发送通知");
                }
                break;
            default:
                // 其他消息直接返回确认
                out.println("收到消息: " + message);
        }
    }
    
    // 发送消息给客户端
    public void sendMessage(String message) {
        out.println(message);
    }
    
    public String getRole() {
        return role;
    }
    
    public String getUserId() {
        return userId;
    }
}
    